package ms.unicorn.reasoning.subcribers;

import java.util.ArrayList;
import java.util.Collection;

import ms.unicorn.Diagram;
import ms.unicorn.Element;
import ms.unicorn.Entity;
import ms.unicorn.NotificationService;
import ms.unicorn.NotificationService.Subscriber;
import ms.unicorn.NotificationService.Subscription;
import ms.unicorn.Relation;
import ms.unicorn.dsl.ILanguageElement;
import ms.unicorn.dsl.LanguageRegistry;
import ms.unicorn.provider.ElementItemProvider;
import ms.unicorn.reasoning.UnicornDSL;

public class OutlineSubscriber implements Subscriber<Element, Object> {

	public static Collection<Integer> PREFER_CHANNELS = new ArrayList<Integer>(1);
	
	static {
		PREFER_CHANNELS.add(NotificationService.CHANNEL_OUTLINE);
	}
	
	@Override
	public Collection<Integer> getPreferChannels() {
		return PREFER_CHANNELS;
	}

	@Override
	public int hanldeSubscription(Object sender, int channel, Subscription<Element, Object> subscription) {
		Element e = subscription.getData();
		//ILanguageElement le = LanguageRegistry.INSTANCE.getLanguageElement(e);
		switch(subscription.getEvent()) {
		case NotificationService.OUTLINE_TEXT:
			if (UnicornDSL.DECOMPOSE.equals(e.getElementType())) {
				Element parent = e.getIncoming().size() == 1 ? e.getIncoming().get(0).getSource():null;
				ElementItemProvider provider = (ElementItemProvider) sender;
				
				subscription.setResult(String.format("Refines: %s", parent != null ? provider.getText(parent):"<null>"));
			}
			break;
		case NotificationService.OUTLINE_IMAGE:
			if (UnicornDSL.DECOMPOSE.equals(e.getElementType())) {
				ILanguageElement le = LanguageRegistry.INSTANCE.getLanguageElement(UnicornDSL.REFINES);
				subscription.setResult(le.getSmallImage());
			}
			break;
		case NotificationService.OUTLINE_CHILDREN:
			if (e instanceof Diagram) {
				ArrayList<Element> children = new ArrayList<Element>();
				for (Element child: e.getElements())
					if (child instanceof Entity)
						children.add(child);
				subscription.setResult(children);
			}
			if (UnicornDSL.DECOMPOSE.equals(e.getElementType())) {
				ArrayList<Element> children = new ArrayList<Element>();
				for(Relation rel: e.getOutgoing())
					children.add(rel.getTarget());
				subscription.setResult(children);
			}
			break;
		}
		
		return NotificationService.SUBSCRIPTION_NORMAL;
	}

}
